package com.n9.buymsg.service.qqonline;

import com.n9.buymsg.service.qqonline.converter.FilterChain;
import com.n9.buymsg.service.qqonline.converter.PurchaseMessageFilter;
import com.n9.sdk.model.PurchaseMessage;

import java.util.Objects;

/**
 * @Author: ice
 * @Date: 2020-07-06 10:07
 */
public class DefaultFilterChain implements FilterChain {
    private PurchaseMessageFilter[] filters = new PurchaseMessageFilter[0];
    private int filterNumber = 0;
    private int filterPos = 0;
    private PurchaseMessageService purchaseMessageService;

    public DefaultFilterChain(PurchaseMessageService purchaseMessageService) {
        this.purchaseMessageService = purchaseMessageService;
    }

    /**
     * 添加过滤器
     * @param filter
     */
    protected void addFilter(PurchaseMessageFilter filter) {
        if (Objects.isNull(filter)) {
            return;
        }

        PurchaseMessageFilter[] newFilters = this.filters;

        //防止重复添加过滤器
        for (int i = 0; i < newFilters.length; i++) {
            if (newFilters[i] == filter) {
                return;
            }
        }

        if (this.filterNumber == this.filters.length) {
            newFilters = new PurchaseMessageFilter[this.filterNumber + 10];
            System.arraycopy(this.filters, 0, newFilters, 0, this.filterNumber);
            this.filters = newFilters;
        }

        this.filters[this.filterNumber++] = filter;
    }

    @Override
    public void doFilter(PurchaseMessage purchaseMessage) {
        if (this.filterPos < this.filterNumber) {
            PurchaseMessageFilter filter = this.filters[this.filterPos++];
            filter.doFilter(purchaseMessage, this);
        } else {
            purchaseMessageService.save(purchaseMessage);
        }
    }

    public void release() {
        for (int i = 0; i < this.filters.length; i++) {
            this.filters[i] = null;
        }
        this.filters = null;
        this.filterNumber = 0;
        this.filterPos = 0;
        this.purchaseMessageService = null;
    }

}
